package com.ssyc.student.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.base.LazyBaseFragment;
import com.ssyc.common.base.SpKeys;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.BqaManager;
import com.ssyc.common.manager.SrfManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.SPUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.student.R;
import com.ssyc.student.adapter.StTreasuerFoodAdapter;
import com.ssyc.student.bean.StTreasuerFood;
import com.ssyc.student.bean.TreasureChestInfo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;


/**
 * 学生端--百宝箱--美食
 */

public class StudentFoodFragment extends LazyBaseFragment implements SrfManager.OnPullRefreshListener {

    //下拉刷新控件
    private SmartRefreshLayout srf;
    //列表控件
    private RecyclerView rv;
    //列表的数据集合
    private List<StTreasuerFood.DataBean> oldDatas;

    //空视图
    private View emptyView;

    //适配器
    private StTreasuerFoodAdapter adapter;

    public UseFoodHandler mHandler;


    //单例模式
    private static volatile StudentFoodFragment studentFootFragment;

    public static StudentFoodFragment newInstance() {
//        if (studentFootFragment == null) {
//            synchronized (StudentFoodFragment.class) {
//                if (studentFootFragment == null) {
        studentFootFragment = new StudentFoodFragment();
//                }
//            }
//        }
        return studentFootFragment;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_student_food;
    }

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {
        initView(view);
        //请求服务器
        http();
    }

    /**
     * 设置下拉刷新控件
     */
    private void initSrl() {
        SrfManager.setSmartByPullListener(srf, null);
        srf.setPrimaryColors(getResources().getColor(R.color.transparent));
    }


    /**
     * 初始化View
     */
    private void initView(View view) {
        srf = view.findViewById(R.id.srf);
        rv = view.findViewById(R.id.rv);


        mHandler = new UseFoodHandler();
    }


    /**
     * 获取百宝箱食物接口数据的网络请求的方法
     */
    private void http() {

        String acc = SPUtil.getString(getActivity(), SpKeys.ACCOUNT);
        String token = SPUtil.getString(getActivity(), SpKeys.TOKEN1);

        Map<String, String> map = new HashMap<>();
        map.put("type", "4");
        map.put("platform", "8");
        map.put("acc", acc);
        map.put("role", "0");
        map.put("apptoken", token);
        map.put("allboxitem", "0");
        HttpUtils.post(HttpAdress.FEED, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                showError();
                UiUtils.Toast(BaseApplication.ERROR, false);

            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    //解析返回服务器返回的JSON数据
                    showContent();
                    StTreasuerFood info = GsonUtil.jsonToBean(response, StTreasuerFood.class);

                    Log.i("test", "百宝箱食物：" + response);
                    if ("200".equals(info.getState())) {
                        if (null != info) {

                            oldDatas = info.getData();
                            //首次加载
                            //设置rv
                            initRv();

                            //设置下拉控件
                            initSrl();

                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("test", "解析服务器返回数据异常");
                }
            }
        });
    }

    /**
     * 设置列表
     */
    private void initRv() {
        emptyView = View.inflate(getContext(), R.layout.st_rv_treasure_food_empty, null);
        adapter = new StTreasuerFoodAdapter(getActivity(), getContext(),
                R.layout.student_rv_common_treasure_food, oldDatas, mHandler);
        //设置横向的布局管理器
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 1);
        BqaManager.setRv(emptyView, gridLayoutManager, getContext(), adapter, rv, null);
    }


    private Handler handler = new Handler();

    /**
     * 下拉刷新
     *
     * @param refreshlayout
     */
    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
//                List<StTreasuerFood.DataBean> newDatas = new ArrayList<>();
//                for (int i = 0; i < 7; i++) {
//                    newDatas.add((StTreasuerFood.DataBean) new StTreasuerFood().getData());
//                }
                BqaManager.updateRvBySmf(BqaManager.PULLREFRESH, srf, rv, oldDatas, oldDatas, adapter);


            }
        }, 2000);
    }

//    /**
//     * 加载更多
//     */
//    @Override
//    public void onLoadMore() {
//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                List<StTreasuerFood.DataBean> newDatas = new ArrayList<>();
//                BqaManager.updateRvBySmf(BqaManager.LOADINDGMORE, srf, rv, oldDatas, newDatas, adapter);
//            }
//        }, 2000);
//    }

    /**
     * Handler回调使用物品
     */
    public class UseFoodHandler extends Handler {
        public Bundle bundle = new Bundle();

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            //接受Json数据
            bundle = msg.getData();
            String json = bundle.getString("json");
            String Energy = bundle.getString("Energy");

            String acc = SPUtil.getString(getActivity(), SpKeys.ACCOUNT);
            String token = SPUtil.getString(getActivity(), SpKeys.TOKEN1);
            String name = SPUtil.getString(getActivity(), SpKeys.NAME);
            String petname = SPUtil.getString(getActivity(), SpKeys.PETNAME);

            Map<String, String> map = new HashMap<>();
            map.put("type", "5");
            map.put("platform", "8");
            map.put("acc", acc);
            map.put("role", "0");
            map.put("apptoken", token);
            map.put("toacc", acc);
            map.put("torole", "0");
            map.put("fromname", name);
            map.put("frompetname", petname);
            map.put("toname", name);
            map.put("frompetname", petname);
            map.put("jsitem", json);

            HttpUtils.post(HttpAdress.FEED, map, this, new HttpUtils.CallBack() {
                @Override
                public void onError(Call call, Exception e, int id) {

                    showError();
                    UiUtils.Toast(BaseApplication.ERROR, false);
                }

                @Override
                public void onResponse(String response, int id) {
                    try {
                        //解析返回服务器返回的JSON数据
                        showContent();
                        TreasureChestInfo info = GsonUtil.jsonToBean(response, TreasureChestInfo.class);

                        Log.i("test", "使用成功" + response);
                        if ("200".equals(info.getState())) {

                            Log.i("test","Energy："+Energy);
                            UiUtils.Toast("宠物增加"+ Energy+"点精力值", false);
                            http();
                        } else {
                            UiUtils.Toast("使用失败，检查网络连接是否正常", false);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("test", "解析服务器返回数据异常");

                    }
                }
            });
        }
    }
}
